<?php

namespace app\common\library;
use Firebase\JWT\JWT;
use think\Cookie;

class JwtToken{
    private $key = "123456789";


    //签发token

    public function setJwtToken($uid){

        $key = $this->key;

        $time = time();

        $token = array(

            "iss" => "http://php.cn",

            "aud" => "http://php.cn",

            'iat' => $time, //签发时间

            'nbf' => $time , //在什么时间之后该jwt才可用

            'exp' => $time + 60*60*24, //过期时间

            "data" => [
                'uid'=>$uid
            ]

        );

        $jwt = JWT::encode($token, $key,'HS256');

        return $jwt;

    }

    //解析token

    public  function getJwtToken($token){
        //为了注销token 加以下if判断代码
        $delete_token = cache('delete_token') ?: [];
        if(in_array($token, $delete_token)){
            //token已被删除（注销）
            return false;
        }
        try{
            $key = $this->key;
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            return $arr['data']->uid;
        }catch (\Exception $e){
            return false;
        }

    }
}